package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.IMemberService;
import com.itheima.service.IReportService;
import com.itheima.service.ISetmealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private IMemberService memberService;

    @Reference
    private ISetmealService setmealService;

    @Reference
    private IReportService reportService;

    /**
     * 工作量统计
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(@RequestBody Map dateMap){
        Map<String,Object> map = new HashMap<String,Object>();
        List<String> months = new ArrayList<String>();
        List<Integer> memberCount = new ArrayList<>();

        String  startTime = (String) dateMap.get("startTime"); // 起始日期
        String  endTime = (String) dateMap.get("endTime"); // 结束日期


        if (startTime != "" && endTime != "" && startTime.length()>0 && endTime.length()>0){
           // 用户选择日期查询
            int indexStart = startTime.lastIndexOf(".");
            int indexEnd = endTime.lastIndexOf(".");
            months = this.getAllMonth(startTime.substring(0,indexStart),endTime.substring(0,indexEnd));
        }else {
            // 用户没有选择日期查询
            Calendar calendar = Calendar.getInstance();
            calendar.add(calendar.MONTH,-12);
            for (int i = 0; i < 12; i++) {
                calendar.add(calendar.MONTH,1);
                months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }
        }
        memberCount = memberService.findCountByBeforeMonth(months);
        map.put("months",months);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }



    /*public Result getMemberReport(){

        Map<String,Object> map = new HashMap<String,Object>();

        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.MONTH,-12);

        List<String> months = new ArrayList<String>();
        for (int i = 0; i < 12; i++) {
            calendar.add(calendar.MONTH,1);
            months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }

        List<Integer> memberCount = memberService.findCountByBeforeMonth(months);

        map.put("months",months);
        map.put("memberCount",memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }
*/

    /**
     * 预约数据统计
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){

        Map<String,Object> data = new HashMap<String,Object>();

        // 查询预约信息
        List<Map<String,Object>> setmealCount = setmealService.findSetmealCount();

        List<String> setmealNames = new ArrayList<String>();
        for (Map<String, Object> map : setmealCount) {
            String  name = (String) map.get("name");
            setmealNames.add(name);
        }

        data.put("setmealNames",setmealNames);
        data.put("setmealCount",setmealCount);

        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
    }


    /**
     * 运营数据统计
     * @return
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String,Object> data = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 下载数据报表
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String,Object> result = reportService.getBusinessReportData();

            String  reportDate = (String) result.get("reportDate");

            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");

            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");

            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");

            // 获得excel模板文件绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "report_template.xlsx";

            // 读取模板文件对象创建表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            XSSFSheet sheet = workbook.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate); // 日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember); // 当日新增会员数
            row.getCell(7).setCellValue(totalMember); // 当日新增会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember); // 本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember); // 本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber); // 今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber); // 今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber); // 本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber); // 本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber); // 本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber); // 本月到诊数

            int rowNum = 12;
            for (Map<String, Object> map : hotSetmeal) {
                String  name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");


                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name); // 套餐名称
                row.getCell(5).setCellValue(setmeal_count); // 预约数量
                row.getCell(6).setCellValue(proportion.doubleValue()); // 预约占比
            }

            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");

            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    public List<String> getAllMonth(String startTime,String endTime){

        List<String> list = new ArrayList<String>();
        try{

            Date d1 = new SimpleDateFormat("yyyy.MM").parse(startTime);//定义起始日期

            Date d2 = new SimpleDateFormat("yyyy.MM").parse(endTime);//定义结束日期  可以去当前月也可以手动写日期。

            Calendar dd = Calendar.getInstance();//定义日期实例

            dd.setTime(d1);//设置日期起始时间

            while (dd.getTime().before(d2)) {//判断是否到结束日期

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");

                String str = sdf.format(dd.getTime());

                list.add(str);//添加当月日期到集合

                dd.add(Calendar.MONTH, 1);//进行当前日期月份加1

            }

        }catch (Exception e){
            System.out.println("异常"+e.getMessage());
        }

        return list;
    }
}
